import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../components/Layout.vue'
import { showToast } from '@/utils/toast'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'login',
      component: () => import('../views/LoginView.vue')
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/RegisterView.vue')
    },
    {
      path: '/forgot-password',
      name: 'forgot-password',
      component: () => import('../views/ForgotPasswordView.vue')
    },
    {
      path: '/main',
      component: Layout,
      redirect: '/login',
      meta: { requiresAuth: true },
      children: [
        {
          path: '/home',
          name: 'home',
          component: () => import('../views/HomeView.vue')
        },
        {
          path: '/bill',
          name: 'bill',
          component: () => import('../views/BillView.vue')
        },
        {
          path: '/user-setting',
          name: 'user-setting',
          component: () => import('../views/UserSettingView.vue')
        },
        {
          path: '/budget',
          name: 'budget',
          component: () => import('../views/BudgetView.vue')
        },
        {
          path: '/notifications',
          name: 'notifications',
          component: () => import('../views/NotificationsView.vue')
        },
        {
          path: '/family',
          name: 'family',
          component: () => import('../views/FamilyView.vue')
        }
      ]
    }
  ]
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 检查是否需要登录权限
  if (to.meta.requiresAuth) {
    const token = localStorage.getItem('token')
    if (!token) {
      showToast('请先登录', 'error')
      next('/')
      return
    }
  }
  next()
})

export default router
